<template>
  <div class="content" ref="content" v-if="tableData">
    <el-button type="primary"  @click="backHandler">返回</el-button>
    <el-button
      type="warning"
      @click="approveHandler(route.query.id)"
      v-if="tableData.state == '未审核' && tableData.incomingtype == '0'"
      v-loading.fullscreen.lock="fullscreenLoading"
      ><Icon name="wrench-screwdriver" />审核</el-button
    >
    <el-button type="success" @click="editClick" v-if="tableData.state != '审核成功' && tableData.incomingtype == '0'">保存修改</el-button>
    
    <div id="base" ref="base" style="margin-top: 1rem;">
      <el-descriptions :column="2" border title="基本信息">
        <el-descriptions-item label-class-name="labelClassNAme" class-name="contentClassName" label="采购入库">{{ tableData.warehosnumber }}</el-descriptions-item>
        <el-descriptions-item label-class-name="labelClassNAme" class-name="contentClassName" label="状态">{{ tableData.state }}</el-descriptions-item>
        <el-descriptions-item label-class-name="labelClassNAme" class-name="contentClassName" label="备注">{{ tableData.remarks }}</el-descriptions-item>
        <el-descriptions-item label-class-name="labelClassNAme" class-name="contentClassName" label="回写状态">{{ tableData.writestate }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <div class="table-default" v-if="summaryData">
      <div id="details" ref="details">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="采购入库单明细" name="details">
            <el-table :data="tableData.detailscheck_all" class="mt-3" border>
              <el-table-column prop="fbillno" label="采购单号" width="200" />
              <el-table-column prop="fseq" label="行号" width="70" />
              <el-table-column prop="fsupplierid_number" label="供应商代号" min-width="150" />
              <el-table-column prop="fsupplierid_name" label="供应商名称" width="200" />
              <el-table-column prop="fmaterialid" label="品号" min-width="150" />
              <el-table-column prop="fmaterialname" label="品名" min-width="200" />
              <el-table-column prop="fmaterialmodel" label="规格" min-width="200" />
              <el-table-column prop="funitid_name" label="单位" min-width="80" />
              <el-table-column prop="fqty" label="计划数量" min-width="100" />
              <el-table-column prop="putquantity" label="入库数量" min-width="180" v-if="tableData.state != '已审核'">
                <template #default="scope">
                  <el-input-number v-model="scope.row.putquantity" :min="0.01" />
                </template>
              </el-table-column>
              <el-table-column prop="putquantity" label="入库数量" min-width="100" v-if="tableData.state == '已审核'">
                <template #default="scope">
                  {{ Number(scope.row.putquantity) }}
                </template>
              </el-table-column>
              <el-table-column prop="barcode" label="条码" min-width="200" />
              <el-table-column prop="FNumber" label="仓库代号" min-width="130" />
              <el-table-column prop="FName" label="仓库名称" min-width="130" />
              <el-table-column prop="warehousecode" label="库位代码" min-width="130" />
              <el-table-column prop="repositoryname" label="库位名称" min-width="130" />
              <el-table-column prop="caigoucreator_id" label="创建者" min-width="130" />
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="品号汇总" name="summary">
            <el-table :data="summaryData" class="mt-3" border>
              <el-table-column prop="fbillno" label="采购单号" width="200" />
              <el-table-column prop="fseq" label="行号" width="70" />
              <el-table-column prop="fsupplierid_number" label="供应商代号" min-width="150" />
              <el-table-column prop="fsupplierid_name" label="供应商名称" width="200" />
              <el-table-column prop="fmaterialid" label="品号" min-width="200" />
              <el-table-column prop="fmaterialname" label="品名" width="200" />
              <el-table-column prop="fmaterialmodel" label="规格" width="200" />
              <el-table-column prop="funitid_name" label="单位" min-width="80" />
              <el-table-column prop="fqty" label="计划数量" min-width="100" />
              <el-table-column prop="putquantity" label="汇总数量" min-width="100">
                <template #default="scope">
                  {{ Number(scope.row.putquantity) }}
                </template>
              </el-table-column>

              <el-table-column prop="giveaway" label="赠品" min-width="180" v-if="tableData.state != '已审核'">
                <template #default="scope">
                  <el-input-number v-model="scope.row.giveaway" :min="0" :max="scope.row.putquantity" />
                </template>
              </el-table-column>
              <el-table-column prop="giveaway" label="赠品" min-width="80" v-if="tableData.state == '已审核'">
                <template #default="scope">
                  {{ Number(scope.row.giveaway) }}
                </template>
              </el-table-column>
              <el-table-column prop="sub" label="非赠品数量" min-width="100">
                <template #default="scope">
                  {{ Number(scope.row.putquantity) - scope.row.giveaway }}
                </template>
              </el-table-column>
              <el-table-column prop="FNumber" label="仓库代号" min-width="130" />
              <el-table-column prop="FName" label="仓库名称" min-width="130" />
              <el-table-column prop="warehousecode" label="库位代码" min-width="130" />
              <el-table-column prop="repositoryname" label="库位名称" min-width="130" />
              <el-table-column prop="caigoucreator_id" label="创建者" min-width="130" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- </el-scrollbar> -->
    </div>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref,reactive } from 'vue'
import { useGetList } from '/admin/composables/curd/useGetList'
import { useDestroy } from '/admin/composables/curd/useDestroy'
import { useOpen } from '/admin/composables/curd/useOpen'
import { useRouter, useRoute } from 'vue-router'
import detailTableVue from './detaiTable.vue'
import http from '/admin/support/http'
import { ElMessage } from 'element-plus'
import emitter from '/admin/utils/emitter'

const router = useRouter()
const route = useRoute()

const tabName = ref('')

const tableData = ref([])
const summaryData = ref([])


const getDetail = () => {
  const api1 = `purchasing/purchasewarehous/${route.query.id}`
  http.get(api1).then(r => {
    const res = r.data.data.data
    console.log('详情数据', res)
    tableData.value = res
  })
}
const getDetailsAll = () => {
  const api2 = `purchasing/purchasewarehous/${route.query.id}?detailsAll=true`
  http.get(api2).then(r => {
    const res = r.data.data.data
    console.log('汇总数据：', res.data)
    summaryData.value = res.detailscheck_all
  })
}

getDetail()
getDetailsAll()

const fullscreenLoading = ref(false)


console.log('路由参数接收', route.query.id)

const backHandler = () => {
  let routeList = JSON.parse(sessionStorage.getItem('routeList'))
  routeList = routeList.filter(item => item.title != '采购入库详情')
  sessionStorage.setItem('routeList', JSON.stringify(routeList))
  router.push('/purchasing/purchasewarehous')
}
const isMore = ref<boolean>(false)

const activeName = ref('details')
const base = ref(null)
const details = ref(null)
const content = ref()
const currentId = tableData.id

const updateDetail = data => {
  return new Promise((resolve, reject) => {
    http
      .put(`/purchasing/updatedata/${currentId}`, data)
      .then(r => {
        console.log(r.data.data)
        let res = r.data.data
        if ((res.code = '1000')) {
          resolve()
        } else {
          ElMessage({
            message: res.message,
            type: 'error',
          })
        }
      })
      .catch(error => {
        reject(error)
      })
  })
}
const updateDetailsAll = data => {
  return new Promise((resolve, reject) => {
    http
      .put(`/purchasing/summaryupdatedata/${currentId}`, data)
      .then(r => {
        console.log(r.data.data)
        let res = r.data.data

        if ((res.code = '1000')) {
          // ElMessage({
          //   message: res.message,
          //   type: 'success',
          // })
          resolve()
        } else {
          ElMessage({
            message: res.message,
            type: 'error',
          })
        }
      })
      .catch(error => {
        reject(error) // 请求失败时调用reject
      })
  })
}

// 修改
const editClick = () => {
  return new Promise((resolve, reject) => {
    let detailObj = tableData.value.detailscheck_all.map(item => {
      return {
        id: item.id,
        putquantity: item.putquantity,
        purchasewarehousing_id: item.purchasewarehousing_id,
      }
    })
    console.log('详情修改数据：', detailObj)
    console.log('summaryData', summaryData.value)

    let AllObj = summaryData.value.map(item => {
      return {
        giveaway: item.giveaway,
        provisional_id: item.provisional_id || null,
        purchaseorder_id: item.purchaseorder_id,
        purchaseorderschedule_id: item.purchaseorderschedule_id,
        supplier_id: item.supplier_id || null,
        purchasewarehousing_id: item.purchasewarehousing_id,
        inspectionlisttable_id: item.inspectionlisttable_id || null,
      }
    })

    console.log('汇总修改数据：', AllObj)

    const p1 = updateDetailsAll(AllObj)
    const p2 = updateDetail(detailObj)

    Promise.all([p1, p2])
      .then(() => {
        ElMessage.success('修改成功！')
        getDetailsAll()
        resolve() // 所有请求函数都返回resolve后，调用resolve
      })
      .catch(error => {
        reject(error) // 如果任何一个请求函数返回reject，调用reject
      })
  })
}

const approveHandler = id => {
  fullscreenLoading.value = true
  editClick()
    .then(() => {
      setTimeout(() => {
        http
          .put(`/purchasing/purchaseexamine/${id}`)
          .then(r => {
            fullscreenLoading.value = false
            ElMessage({
              message: r.data.message,
              type: 'success',
            })
            getDetail()
            emitter.emit('changepurchasewarehousStatus', { status: true })
          })
          .catch(error => {
            fullscreenLoading.value = false
          })
      }, 1000)
    })
    .catch(error => {
      ElMessage({
        message: '审核请求失败',
        type: 'dangder',
      })
      console.log(error)
      fullscreenLoading.value = false
    })
}

</script>

<style lang="css">
.content {
  padding: 10px;
  background-color: #fff;
}
.backBtn {
  margin: 20px 0;
}
h2 {
  font-weight: bold;
}

.tabs {
  /* padding: 10px 0 0; */
  /* border: 2px solid #000; */
  z-index: 999;
  background-color: #fff;
  position: sticky;
  top: -15px;
}

.tagRow {
  display: inline-block;
  /* border: 1px solid #000; */
  margin: 20px 10px;
}

.tagRow ul {
  display: flex;
  border: 1px solid #eee;
}
.tagRow ul li {
  margin: 0 5px;
  /* border: 1px solid #eee; */
  padding: 5px 10px;
  /* border-radius: 5px; */
}
.active {
  background-color: #409eff;
  color: #fff;
}
.labelClassNAme {
  width: 130px;
}
.contentClassName {
  width: 170px;
}
</style>
